#/usr/bin/perl                                                                                                                           
use POSIX "fmod"; # float modulus
use List::Util qw[min]; # min function

# Do simulation results file globbing
$outputdir = "/home/rumen/simulation1";
$query = $ARGV[0];

# Get all sweeps that match the query
opendir(DIR, $outputdir);
@files = grep { /$query/ } readdir(DIR);
closedir(DIR);
print "a,p,mu,nu,rsm,b,d,nn,t,h,w,rep,day,divergence,max_min\n";
foreach $f (@files) {
    #print STDERR "Processing sweep $f\n";
    $dir = $outputdir."/".$f;    
    opendir(DIR, $dir);    
    @infiles = grep { /rep(\d+)\.log/ } readdir(DIR);
    closedir(DIR);
    
    # Contains all the rep runs number, e.g. if rep45, rep3, rep1 are present, rephash stores 45, 3, 1
    my %rephash = ();   
    foreach $i (@infiles) {
	@repnumber = split (/rep|\./, $i);
	$rephash{$repnumber[1]}=1;
    }
    foreach $run (sort {$a <=> $b} keys %rephash){

	@params = split(/\_*[A-Z]+=/,$f);	
	open(in, $dir."/rep$run.divergence.statistics.log");
	$hdr = <in>;
	while(<in>){
	    chomp;
	    for $j ( 1..11){
		print $params[$j].",";
	    }
	    print $run.",".$_."\n";
	}
	close(in);
    }
}
